﻿using System;
using System.Text;
using limpalex.bbparser.Interfaces;

namespace limpalex.bbparser
{
    partial class Replacement
    {
        private interface IReplacementPart
        {
            void Append(StringBuilder buffer, IParameterList parameterList);
        }

        private class ReplacementText : IReplacementPart
        {
            private readonly string _text;
            public ReplacementText(string text)
            {
                _text = text;
            }

            public void Append(StringBuilder buffer, IParameterList parameterList)
            {
                buffer.Append(_text);
            }
        }

        private class ReplacementParameter : IReplacementPart
        {
            private readonly string _parameter;
            private readonly IAttributeEvaluator _evaluator;

            public ReplacementParameter(string parameter, IAttributeEvaluator evaluator)
            {
                _parameter = parameter;
                _evaluator = evaluator;
            }

            public void Append(StringBuilder buffer, IParameterList parameterList)
            {
                if (_evaluator == null)
                {
                    buffer.Append(parameterList[_parameter]);
                    return;
                }

                if (Array.Exists(_evaluator.SupportedAttributes, name => name.Equals(_parameter, StringComparison.OrdinalIgnoreCase)))
                    buffer.Append(_evaluator.EvaluateAttribute(parameterList, _parameter));
                else
                    buffer.Append(parameterList[_parameter]);
            }
        }
    }
}
